// guards/jwt-auth.guard.ts
import {
  Injectable,
  CanActivate,
  ExecutionContext,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
import { ApiException } from '../../common/filter/http-exception/api.exception';
import { ApiErrorCode } from '../../common/enums/api-error-code.enum';
import { Request } from 'express';
import { Reflector } from '@nestjs/core';
// import { AuthGuard } from '@nestjs/passport';
interface JwtPayload {
  sub: string;
  username: string;
  // 根据实际情况添加其他字段
}

@Injectable()
export class JwtAuthGuard implements CanActivate {
  constructor(
    private reflector: Reflector,
    private jwtService: JwtService,
    private configService: ConfigService,
  ) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request: Request = context.switchToHttp().getRequest();
    const isPublic = this.reflector.getAllAndOverride<string[]>('isPublic', [
      context.getClass(),
      context.getHandler(),
    ]);

    if (isPublic) {
      return true;
    }

    const token = this.extractTokenFromHeader(request);
    if (!token) throw new HttpException('验证不通过', HttpStatus.FORBIDDEN);
    try {
      const payload = await this.jwtService.verifyAsync<JwtPayload>(token, {
        secret: this.configService.get('JWT_SECRET'),
      });
      request['user'] = payload;
    } catch {
      throw new ApiException('Token 验证失败', ApiErrorCode.GUOQI_NOTEXIST);
    }
    return true;
  }

  private extractTokenFromHeader(request: Request): string | undefined {
    const authHeader = request.headers.authorization;
    if (!authHeader) {
      return undefined; // 如果没有 authorization 头，直接返回 undefined
    }

    const [type, token] = authHeader.split(' ');

    if (type !== 'Bearer' || !token) {
      return undefined; // 如果 type 不是 'Bearer' 或者 token 不存在，返回 undefined
    }

    return token; // 返回 token
  }
}
